package com.ophiux.auth.controller;

import cn.hutool.core.util.IdUtil;
import com.ophiux.auth.dto.LoginReqVo;
import com.ophiux.auth.dto.TokenLoginResp;
import com.ophiux.auth.util.JwtUtils;
import com.ophiux.common.core.base.Result;
import com.ophiux.common.core.constant.CacheConstants;
import com.ophiux.common.core.constant.SecurityConstants;
import com.ophiux.common.redis.service.RedisUtils;
import com.ophiux.common.security.service.OphiuxUserDetailsService;
import com.ophiux.system.api.feign.RemoteUserService;
import com.ophiux.system.model.dto.LoginUser;
import com.ophiux.system.model.dto.UserInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequiredArgsConstructor
@RequestMapping("/tokenLogin")
@Deprecated
public class AuthController {
    private final static long EXPIRE_TIME = CacheConstants.EXPIRATION;
    private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;
//    private final AuthenticationManager authenticationManager;
    private final JwtUtils jwtUtils;
    private final RemoteUserService remoteUserService;

    private final CacheManager cacheManager;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private OphiuxUserDetailsService ophiuxSystemUserDetailsService;

    @RequestMapping("/login")
    public Result<TokenLoginResp> authenticate(LoginReqVo request) {
//        authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword()));
        Result<UserInfo> userInfoResult = remoteUserService.info(request.getUsername(), SecurityConstants.FROM_IN);
        UserDetails userDetails = ophiuxSystemUserDetailsService.getUserDetails(userInfoResult);

        if (userInfoResult != null && userInfoResult.isSuccess()) {
            UserInfo userInfo = userInfoResult.getData();
            // Jwt存储信息
            String token = IdUtil.fastUUID().replaceAll("-", "");
            Map<String, Object> claimsMap = new HashMap<String, Object>();
            claimsMap.put(SecurityConstants.USER_KEY, token);
            claimsMap.put(SecurityConstants.DETAILS_USER_ID, userInfo.getSysUser().getUserId());
            claimsMap.put(SecurityConstants.DETAILS_USERNAME, userDetails.getUsername());

            LoginUser loginUser = new LoginUser();
            loginUser.setRoles(userInfo.getRoles());
            loginUser.setPermissions(userInfo.getPermissions());
            loginUser.setToken(token);
            loginUser.setSysUser(userInfo.getSysUser());
            loginUser.setUserid(userInfo.getSysUser().getUserId());
            refreshToken(loginUser);

            // 接口返回信息
            TokenLoginResp loginResp = new TokenLoginResp();
            String accesstoken = jwtUtils.generateToken(userDetails, claimsMap);
            loginResp.setAccessToken(accesstoken);
            loginResp.setExpireTime(EXPIRE_TIME);

            String userKey = jwtUtils.getUserKey(accesstoken);
            String userId = jwtUtils.getUserId(accesstoken);

            return Result.success(loginResp);
        }
        return Result.fail("登录失败");
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + EXPIRE_TIME);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisUtils.setCacheObject(userKey, loginUser, EXPIRE_TIME, TimeUnit.SECONDS);
    }

    private String getTokenKey(String token) {
        return ACCESS_TOKEN + token;
    }
}
